package com.qf.utils;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @Description: 公用常量
 * @Data: 2022/9/1 8:43
 * @Pacakge: com.qf.utils
 * @ClassName: ConnectionUtils
 * @Author: fan
 */
public class ConnectionUtils {
    //根据线程获取数据库连接对象
    private ThreadLocal<Connection> t1 = new ThreadLocal<>();
    //从数据源中获取数据库连接对象
    private DataSource dataSource;
    //set注入
    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }
    //获取数据库连接对象
    public Connection getConnection(){
        try {
            Connection connection = t1.get();
            if (connection == null){
                connection = dataSource.getConnection();
                t1.set(connection);
            }
            return connection;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    //释放资源
    public void removeConnection(){
        t1.remove();
    }
}
